<template>
  <page-meta :page-style="'overflow:'+(isTouchScroll ? 'hidden' : 'visible')"></page-meta>
  <view>
    <view class="banner">
      <view class="shop-banner">
        <image class="img-shoplogo" :src="$getImg('iassCashier/shop.png')" mode="aspectFill"></image>
        <image class="img-banner" :src="$getImg('iassCashier/top_bg.png')" mode="widthFix"></image>
      </view>
      <view class="shop-title-box">
        <view class="shop-title">{{shop.cnAbbr}}</view>
        <view class="shop-title staff-name" v-if="shop.staffName">{{shop.staffName}}</view>
      </view>
    </view>
    <view class="amount">
      <view class="amount-tip">消费总金额</view>
      <view class="amount-input">
        <view class="amount-text">￥</view>
        <input class="amount-text amount-ipt" placeholder="请输入金额" focus type="digit"
          placeholder-class="placeholder-class" maxlength="11" :disabled="!isTrue(shop.codeType)"
          v-if="isTrue(shop.codeType)" inputmode="decimal" v-model="shop.totalFee" @input="amountInput"
          @blur="amountInputBlur" />
        <view class="amount-text amount-ipt" v-else>{{shop.totalFee}}</view>
      </view>
    </view>
    <view class="ele-box" v-if="isTrue(shop.randomRemarks)">
      <remark-form ref="remarkForm" @popup-change="popupChange" :prompt-list="merchantPromptMessageList"
        :out-number="outNumber" :flat-map-flag="shop.flatMapFlag" :auth-remark="shop.authRemark" />
    </view>
    <view class="ele-box" v-if="isTrue(shop.remarkOptionsFlag)">
      <remark-option ref="remarkOption" @popup-change="popupChange" :mchntCd="shop.mchntCd" :codeId="codeId"
        :options="merchantOptionMessageList" />
    </view>
    <view class="ele-box" v-if="shop.requiredFlag != '2'">
      <invoice-Form ref="invoiceForm" @popup-change="popupChange" :required-flag="shop.requiredFlag"
        :required-invoice="shop.requiredInvoice" />
    </view>
    <view class="ele-box" v-if="payMethodsChooseShow">
      <choose-pay ref="choosePay" @change="payWayChange" :ningLaiHuaFlag="ningLaiHuaFlag"
        :bankAppPayFlag="bankAppPayFlag" :paymentPrompt="paymentPrompt" />
    </view>
    <view class="ele-box" v-if="isTrue(shop.beautyLifeFlag,'0') && channelType == 1">
      <payment-coupons ref="paymentCoupons" :coupons="availableCouponList" :shop="shop" :all-disabled="btnDisabled"
        @change="selectCouponChange" @get-phone="getPhone" :codeId="codeId" />
    </view>
    <view class="confirm-text" style="margin-top: 10px;">温馨提示：</view>
    <view class="confirm-text" style="padding-bottom: 320rpx;">请您仔细核对商户信息和消费总金额，确认无误后支付</view>
    <BottomButton>
      <view class="comfirm-box">
        <view class="act-amount" v-show="couponList.length > 0">
          <text class="act-amt-text">实付总金额(元)
            <text style="font-weight: 700; margin-left: 5px; font-size: 14px;">{{paymentAmt}}</text>
          </text>
          <text class="act-amt-text" style="color: #FF8400; margin-left: 7px;">已优惠{{deductionAmt}}元</text>
        </view>
        <button class="confirm-btn" :class="!btnDisabled ? 'btn-disabled' : ''" :disabled="!btnDisabled"
          @click="confirm">确认支付</button>
      </view>
    </BottomButton>
  </view>
</template>

<script>
  let payWay = '';
  // #ifdef MP-WEIXIN
  payWay = '1'; //微信支付方式
  // #endif
  // #ifdef MP-ALIPAY
  payWay = '2'; //支付宝方式
  // #endif
  import {
    mapGetters
  } from 'vuex';
  import {
    getPayInfo,
    createOrder,
    callPayment,
    calcPaymentAmt
  } from "./api/pay.js";
  import {
    checkType,
    isEmpty,
    debounce,
    getAuthCode
  } from "@/common/util.js"
  import RemarkForm from './components/RemarkForm.vue';
  import RemarkOption from './components/RemarkOption.vue';
  import ChoosePay from './components/ChoosePay.vue';
  import InvoiceForm from './components/InvoiceForm.vue';
  import PaymentCoupons from './components/PaymentCoupons.vue';
  import BottomButton from './components/BottomButton.vue';
  export default {
    components: {
      RemarkForm,
      RemarkOption,
      InvoiceForm,
      ChoosePay,
      PaymentCoupons,
      BottomButton
    },
    computed: {
      ...mapGetters(["configInfo", "channelType", 'systemInfo']),
      btnDisabled() {
        return parseFloat(this.shop.totalFee) > 0 && !this.isLoading
      },
      payMethodsChooseShow() {
        return this.ningLaiHuaFlag == '0' || this.bankAppPayFlag == '0'
      }
    },
    data() {
      return {
        isTouchScroll: false, // popup弹出，禁止页面滑动
        merchantPromptMessageList: [], //商户备注
        merchantOptionMessageList: [], //备注选项
        advertMessageList: [], //广告列表
        availableCouponList: [], //美好生活卡券信息
        shop: {
          advertFlag: "0", // 1:有广告 0 无广告
          authRemark: "2", //是否强制备注 1:是 2:否
          codeType: "2", //1:静态码 2:定额静态码 0 动态码
          flatMapFlag: "0", // 备注是否平铺 1:开启平铺 2：不平铺
          keyBoard: "1", //是否启用易收宝键盘 1：开启 2：关闭
          randomRemarks: "0", // 备注/自定义输入 1:开启 0 ：不开启
          remarkOptionsFlag: "2", // 是否开启备注选项 1:开启 2:关闭
          requiredFlag: "2", // 1:是强制开票 0:不强制 2:不开票
          requiredInvoice: "", // 开通开票类型有哪些
          cnAbbr: "", //门店名称
          totalFee: "", //订单金额
          ttgFlag: "0", // 是否淘淘谷 1:ttg 0:不是
          thirdUserID: "", // 第三方用户id
          phone: "", //// 用户手机号
          mchntCd: '', //商户号
          staffName: '', //用户名/店员名
          beautyLifeFlag: '1', // 美好生活优惠券开通标识 1：关闭 0：开启
          beautyLifeStoreId: '', // 美好生活店铺id
        },
        codeId: '', // 二维码ID
        ningLaiHuaFlag: "1", //   宁来花标识  0:支持 1:不支持
        bankAppPayFlag: "1", //   宁波银行支付方式标识  0:支持 1:不支持
        //以上接口返回门店信息 ===end====
        authCode: "", //授权:code
        appUpIdentifier: "", //银联云闪付参数:appUpIdentifier
        checkCode: '0', //是否 校验二维码 静转动 需要校验:1 不需要校验 :0
        // 下单参数变量 ===end===
        remarkOption: '', // 选择的备注选项
        invoiceData: {}, //发票表单信息
        outNumber: "", //链接携带订单号
        dynFlag: '', //是否是无收银台收款标志
        paymethodschooseshow: false, // 支付方式选择组件是否展示--宁来花 || 宁波银行的标识决定
        payWay,
        timerDebounceFunc: null,
        timerCouponChangeFunc: null,
        paymentAmt: 0, // 优惠后实际支付金额
        deductionAmt: 0, // 优惠金额
        couponList: [], // 美好生活优惠券选中列表
        repeatPayFlag: 0, // 美好生活优惠券冻结失败，是否以原金额支付0 否，1是
        paymentPrompt: "", //宁来花支付提示
        isLoading: false,
      };
    },
    onLoad(query) {
      let enterQuery = uni.getEnterOptionsSync(),
        qrcodeUrl = '';
      if (payWay == '1') qrcodeUrl = enterQuery.query.q;
      if (payWay == '2') qrcodeUrl = enterQuery.query.qrCode;
      qrcodeUrl = decodeURIComponent(qrcodeUrl);
      console.log('enterQuery===>', enterQuery)
      uni.hideHomeButton()
      uni.clearStorageSync()
      this.codeId = this.getUrlQuery(qrcodeUrl, 'qrCode')
      this.appUpIdentifier = this.getUrlQuery(qrcodeUrl, 'appUpIdentifier')
      this.dynFlag = this.getUrlQuery(qrcodeUrl, 'dynFlag')
      this.outNumber = this.getUrlQuery(qrcodeUrl, 'outNumber')
      let version = this.configInfo.envVersion;
      if (version == "develop") {
        // this.codeId = '20230525091252PQ8E7C494499154252' // 昭 
        // this.codeId = '20200611195549PQ020877307FE6426F' // 栋
        // this.codeId = '20240321163623SQ6FF60AB6E804436C'
        // this.codeId = '20240521193631SQF25F817C2CA04A64'
        // this.codeId = '20240223094303SQ7FF8410B8ADA4485'
        // this.codeId = "20240521084142SQFFA67ECFB8BD4CE7"
        this.codeId = "332038170110000/2024052211131793117880087351296u"
      }
      if (isEmpty(this.codeId)) {
        uni.redirectTo({
          url: '/pages/iassCashier/error?errMsg=请扫描商家收款码进入',
        })
      } else {
        this.getShopInfo()
        this.timerDebounceFunc = debounce(() => {
          this.placeOrder()
        }, 200, true)
        this.timerCouponChangeFunc = debounce(() => {
          this.selectCouponChange(this.couponList)
        }, 200)
      }
    },
    methods: {
      // url参数解码
      getUrlQuery(query, queryName) {
        if (!query.includes(queryName)) return '' //字符串类型--空字符串
        if (query === 'undefined') return ''
        let regExp = new RegExp('^.*[?&]' + queryName + '=([^&=?]*)&?.*$', '')
        let queryData = query.replace(regExp, '$1')
        if (queryData.startsWith('/')) {
          queryData = queryData.slice(1);
        }
        return queryData
      },
      isTrue(val, val2 = '1') {
        return !isEmpty(val) && val == val2
      },
      // 查询二维码店铺信息
      async getShopInfo(query) {
        try {
          let r = await getAuthCode();
          this.authCode = r.code;
          let parmas = {
            authCode: this.authCode,
            channelType: this.channelType,
            codeId: this.codeId,
            wxMiniProgramFlag: '1', //小程序标识
          }
          let res = await getPayInfo(parmas)
          this.getKeyVal(res)
        } catch (err) {
          this.$toast(err.respMsg || '系统异常')
        }
      },
      // 店铺信息赋值
      getKeyVal(data) {
        if (this.isTrue(data.randomRemarks) && !isEmpty(this.outNumber)) {
          data.merchantPromptMessageList[0].content = this.outNumber
        }
        let keyArr = ['merchantPromptMessageList', 'merchantOptionMessageList', 'advertMessageList',
          'availableCouponList', 'authRemark',
          'ningLaiHuaFlag', 'bankAppPayFlag', 'paymentPrompt'
        ]
        keyArr.forEach(key => {
          if (!isEmpty(data[key])) this[key] = data[key]
        })
        Object.keys(this.shop).forEach(key => {
          let val = data[key];
          if (!isEmpty(val)) {
            if (key === 'totalFee' && val == 0) val = '';
            this.shop[key] = val
          }
        })
      },
      popupChange(e) {
        this.isTouchScroll = e.show
      },
      // 格式化输入金额
      amountInput(e) {
        let val = this.shop.totalFee;
        val = val.replace(/[^\d.]/g, '')
        val = val.replace(/^\./g, '')
        val = val.replace(/\.{2,}/g, '.')
        val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
        if (val.indexOf('.') < 0 && val.length > 0) val = `${parseFloat(val)}`
        this.$nextTick(() => {
          this.shop.totalFee = val
          this.timerCouponChangeFunc()
        });
        return val
      },
      // 金额输入框失焦
      amountInputBlur() {
        this.selectCouponChange(this.couponList)
      },
      // 支付方式变化
      payWayChange(data) {
        this.payWay = data.type;
      },
      // 获取手机号
      getPhone(data) {
        this.shop.phone = data.phone || '';
        this.availableCouponList = data.availableCouponList || [];
        if (isEmpty(data.availableCouponList)) {
          this.$toast('暂无可用优惠券')
        }
      },
      // 选择优惠券计算支付金额
      async selectCouponChange(couponList) {
        this.couponList = couponList
        if (isEmpty(couponList)) {
          this.paymentAmt = Number(this.shop.totalFee).toFixed(2)
          this.deductionAmt = 0
          return
        }
        try {
          let parmas = {
            transAmount: this.shop.totalFee,
            couponList,
            thirdUserID: this.shop.thirdUserID,
            codeId: this.codeId
          }
          let res = await calcPaymentAmt(parmas)
          let paymentAmt = res.paymentAmt || 0;
          let deductionAmt = res.deductionAmt || 0;
          this.paymentAmt = Number(paymentAmt).toFixed(2);
          this.deductionAmt = Number(deductionAmt).toFixed(2);
        } catch (e) {
          this.$toast(e.respMsg)
          this.$refs.paymentCoupons.clearCheckedList()
        }
      },
      // 卡券核销失败,支付时弹窗提示
      showModalRepeatPay() {
        return new Promise((resolve, reject, defaults) => {
          uni.showModal({
            title: '提示',
            content: '卡券核销失败，是否以原金额支付？',
            confirmColor: '#FF9900',
            success: (res) => {
              if (res.confirm) {
                this.couponList = []
                resolve(1)
              } else {
                resolve(0)
              }
            }
          });
        })
      },
      // 确认支付
      confirm() {
        this.timerDebounceFunc()
      },
      // 下单支付
      async placeOrder() {
        try {
          if (this.isTrue(this.shop.randomRemarks)) {
            let resRemarkForm = this.$refs.remarkForm.validateForm()
            if (!resRemarkForm) return
            this.merchantPromptMessageList = resRemarkForm
          }
          if (this.isTrue(this.shop.remarkOptionsFlag)) {
            let remarkOption = this.$refs.remarkOption.validateForm()
            if (!remarkOption) return
            this.remarkOption = remarkOption
          }
          if (this.shop.requiredFlag != '2') {
            let resInvoiceForm = this.$refs.invoiceForm.validateForm()
            if (!resInvoiceForm) return
            this.invoiceData = resInvoiceForm
          }
          if (this.isLoading) return
          this.isLoading = true
          let r = await getAuthCode();
          this.authCode = r.code;
          let orderParams = {
            wxMiniProgramFlag: '1', //小程序标识
            authCode: this.authCode, // 授权code
            channelType: this.channelType, //支付渠道 1 微信；2 支付宝 3 银联云闪付
            codeId: this.codeId, // 二维码id
            totalFee: this.shop.totalFee, // 下单金额
            checkCode: this.checkCode, // 校验二维码静转动 需要校验:1 不需要校验 :0
            remarkOptionContent: this.remarkOption, //备注选项
            promptMessageList: this.merchantPromptMessageList, //备注内容
            invoice: this.invoiceData, //开票信息
            gpsFlag: "0", // 是否需要定位信息，0 不需要，1 需要
            thirdUserId: this.shop.thirdUserID, //：第三方用户id
            appUpIdentifier: this.appUpIdentifier, //银联渠道参数
            authRemark: this.shop.authRemark,
            outOrderNumber: this.outNumber,
            nlhFlag: this.payWay == '13' ? '1' : '0',
            nbcbPayFlag: this.payWay == '8' ? '1' : '0',
            couponList: this.couponList,
            payWay: this.payWay,
            repeatPayFlag: this.repeatPayFlag,
          }
          let res = await createOrder(orderParams),
            url = '';
          if (res.repeatPayFlag == 1) {
            let res = await this.showModalRepeatPay()
            if (res == 1) {
              this.repeatPayFlag = 1;
              this.couponList = []
              this.isLoading = false
              this.placeOrder()
            }
            return
          }
          if (res.dynFlag == '1') {
            uni.setStorageSync("dynVo", res.dynVo)
            uni.setStorageSync("orderParams", orderParams)
            uni.setStorageSync("orderNo", res.dynVo.outTradeId)
            uni.setStorageSync("mchntCd", this.shop.mchntCd)
            url = `/pages/iassCashier/dynamic?orderNo=${res.dynVo.outTradeId}&mchntCd=${this.shop.mchntCd}`;
          } else if (res.gpsFlag == '1') {
            uni.setStorageSync("orderParams", orderParams)
            url = `/pages/iassCashier/location?orderNo=${res.orderNo}`;
          } else if (this.payWay != '1' && this.payWay != '2') {
            let urlKey = this.payWay == '13' ? 'returnUrl' : 'payUrl';
            let encodedReturnUrl = encodeURIComponent(res[urlKey]);
            // let testUrl = 'https://aaph.nbcb.com.cn/iscene/isceneMicroappView/#/login?redirect=%2FuserManage'
            // let testUrl = 'https://aapw.nbcb.com.cn/ipayPcView/#/login'
            // let encodedReturnUrl = encodeURIComponent(testUrl);
            url = `/pages/iassCashier/payView?url=${encodedReturnUrl}`
          }
          if (isEmpty(url)) {
            callPayment(res)
          } else {
            uni.redirectTo({
              url
            })
          }
        } catch (err) {
          this.$toast(err.respMsg || '系统异常')
        }
      }
    }
  }
</script>

<style lang="scss">
  .img-common {
    display: block;
  }

  .banner {

    .shop-banner {
      position: relative;

      .img-banner {
        display: block;
        width: 100%;
        height: 201rpx;
      }

      .img-shoplogo {
        display: block;
        width: 110rpx;
        height: 110rpx;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 50%;
        background-color: #fff;
      }
    }

    .shop-title-box {
      padding: 30rpx 24rpx;
      background-color: #fff;

      .shop-title {
        font-size: 36rpx;
        font-weight: 700;
        text-align: center;
        word-break: break-all;
        line-height: 46rpx;
      }

      .staff-name {
        font-size: 32rpx;
        margin-top: 10rpx;
      }
    }

  }

  .amount {
    padding: 0 12px 10px;
    background-color: #fff;

    .amount-tip {
      padding: 5px 0;
      font-size: 13px;
      line-height: 20px;
      color: #8a8a8a;
    }

    .amount-input {
      display: flex;
      align-items: center;
      padding-bottom: 5px;
      border-bottom: 1rpx solid #ededf0;

      .amount-text {
        font-size: 28px;
        color: #333;
        line-height: 34px;
      }

      .amount-ipt {
        flex: 1;
        height: 34px;
        border: none;
      }

      .amount-ipt:disabled {
        color: #333;
      }

      .placeholder-class {
        font-size: 20px;
        color: #ccc;
      }
    }
  }

  .ele-box {
    background-color: #fff;
    margin-top: 20rpx;
  }

  .confirm-text {
    font-size: 13px;
    padding: 0 12px;
    line-height: 20px;
    color: #979aa5;
  }

  .comfirm-box {
    .act-amount {
      margin-bottom: 6px;
      word-break: break-all;

      .act-amt-text {
        font-size: 12px;
        line-height: 20px;
        color: #595e70;
      }

      .act-amt {
        font-size: 15px;
        padding: 0 5px;
        font-weight: 700;
      }
    }

    .confirm-btn {
      display: block;
      background: linear-gradient(90deg, #FF9900 0%, #FF8400 100%);
      border-radius: 22px;
      font-size: 16px;
      height: 44px;
      line-height: 44px;
      color: #fff;
      width: 100%;
    }

    .btn-disabled {
      opacity: .7;
      background: linear-gradient(90deg, #FF9900 0%, #FF8400 100%);
      color: rgba(0, 0, 0, .3);
    }

  }
</style>